<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;

class Warehouse extends Model
{
    //仓库的列表
    public function getsetings($res)
    {
        $page = $res['page'];
        $limit = $res['pageSize'];
        $data = $this->page($page, $limit)->select();
        foreach ($data as $datakey => $dataval) {
            //编辑者
            $data[$datakey]['updatename'] = getinfo($dataval['update_id'], 'admin')['nickname'];
            $data[$datakey]['update_date'] = getTimeDate($dataval['update_at'], 12);//更新时间
            //获取该地区
            $data[$datakey]['addressname'] = getinfo($dataval['country_id'], 'country')['name'] . '/' . getinfo($dataval['province_id'], 'provinces')['name'];
        }
        $count = $this->count();
        return array('count' => $count, 'data' => $data);
    }

    //仓库的添加与编辑
    public function addeditseting($data)
    {
        $ckdata = notEmpty(['name' => '名称', 'province_id' => '省份']);
        if ($ckdata['status'] == 2) {
            return $ckdata;
        }
        //添加仓库
        $name = trim($data['name']);
        if ($data['act'] == 'setingadd') {
            $info = $this->where('name', $name)->find();
            if ($info) {
                return array('msg' => $data['name'] . lang("already_exists"), 'status' => 3);
            }
            unset($data['id']);
            $data['create_id'] = $data['update_id'] = session('userid');
            $data['create_at'] = $data['update_at'] = time();
            $setingid = $this->strict(false)->insertGetId($data);//仓库表
            if ($setingid) {
                return array('msg' => $name . lang("added_successfully"), 'status' => 1);
            } else {
                return array('msg' => $name . lang("add_failed"), 'status' => 0);
            }
        } elseif ($data['act'] == 'setingedit') {
            unset($data['act']);
            $data['update_id'] = session('userid');
            $data['update_at'] = time();
            $setingid = $this->where('id', $data['id'])->update($data);//仓库表
            if ($setingid !== false) {
                return array('msg' => $name . lang("edited_successfully"), 'status' => 1);
            } else {
                return array('msg' => $name . lang("edit_failed"), 'status' => 0);
            }
        }
    }

    //仓库的删除
    public function delsetings($data)
    {
        $info = Db::name('store')->where('warehouse_id', $data['id'])->select();
        if ($info) {
            return array('msg' => '该仓库含有库存，不允许删除', 'status' => 0);
            exit();
        }
        //删除距离表
        Db::name('warehouse_distance')->where('warehouse_id', $data['id'])->delete();
        //人员表
        Db::name('warehouse2admin')->where('warehouse_id', $data['id'])->delete();
        //位置表
        Db::name('warehouse_place')->where('warehouse_id', $data['id'])->delete();
        //区域表
        Db::name('warehouse_area')->where('warehouse_id', $data['id'])->delete();
        $retseting = $this->where('id', $data['id'])->delete();//仓库表
        if ($retseting) {
            return array('msg' => $data['name'] . lang("cleared_successfully"), 'status' => 1);
        } else {
            return array('msg' => $data['name'] . lang("clear_failed"), 'status' => 0);
        }
    }

    //处理仓库的人员编制
    public function sunadminbtn($res)
    {
        Db::name('warehouse2admin')->where('warehouse_id', $res['warehouse_id'])->delete();//清除该仓库的数据
        if (isset($res['admin_id'])) {
            //清除该员工在所在的仓库
            $mapadmin['admin_id'] = array('in',implode(',',$res['admin_id']));
            Db::name('warehouse2admin')->where($mapadmin)->delete();
            foreach ($res['admin_id'] as $reskey => $resval) {
                $insert['warehouse_id'] = $res['warehouse_id'];
                $insert['admin_id'] = $resval;
                Db::name('warehouse2admin')->insert($insert);
            }
        }
        //更新送货员工的仓库id
        $admindata = getables('warehouse2admin');
        foreach ($admindata as $admindatakey => $admindataval) {
            Db::name('deliveryman')->where('admin_id', $admindataval['admin_id'])->update(['warehouse_id' => $admindataval['warehouse_id']]);
        }
        return array('msg' => '设置成功', 'status' => 1);
    }

    //设置仓库的位置
    public function placeadddel($data)
    {
        $admin = session('admin');
        if ($data['act'] == 'add') {
            $ckdata = notEmpty(['name' => '位置名称']);
            if ($ckdata['status'] == 2) {
                return $ckdata;
            } else {
                $resdata['create_id'] = $resdata['update_id'] = session('userid');
                $resdata['create_at'] = $resdata['update_at'] = time();
                $resdata['mangname'] = $admin['nickname'];
                $resdata['update_date'] = getTimeDate(time(), 12);
                return array('msg' => $data['name'] . lang("added_successfully"), 'status' => 1, 'resdata' => $resdata);
            }
        } elseif ($data['act'] == 'sub') {
            //保存
            Db::name('warehouse_place')->where('warehouse_id', $data['warehouse_id'])->delete();
            if (isset($data['placelist']) && $data['placelist']) {
                foreach ($data['placelist'] as $datakeys => $datavals) {
                    if ($datavals['id']) {
                        $update['id'] = $datavals['id'];
                        $update['warehouse_id'] = $datavals['warehouse_id'];
                        $update['name'] = $datavals['name'];
                        $update['remarks'] = $datavals['remarks'];
                        $update['create_id'] = $datavals['create_id'];
                        $update['update_id'] = $datavals['update_id'];
                        $update['create_at'] = $datavals['create_at'];
                        $update['update_at'] = $datavals['update_at'];
                        Db::name('warehouse_place')->insert($update);
                    } else {
                        Db::name('warehouse_place')->strict(false)->insert($datavals);
                    }
                }
                $retid = 1;
            } else {
                $retid = 1;
            }
            if ($retid) {
                return array('msg' => lang("edited_successfully"), 'status' => 1);
            } else {
                return array('msg' => lang("edit_failed"), 'status' => 0);
            }
        }
    }

    //设置仓库的区域
    public function areaadddel($data)
    {
        $admin = session('admin');
        if ($data['act'] == 'add') {
            $ckdata = notEmpty(['name' => '区域名称', 'volume' => '体积']);
            if ($ckdata['status'] == 2) {
                return $ckdata;
            } else {
                $resdata['create_id'] = $resdata['update_id'] = session('userid');
                $resdata['create_at'] = $resdata['update_at'] = time();
                $resdata['mangname'] = $admin['nickname'];
                $resdata['update_date'] = getTimeDate(time(), 12);
                return array('msg' => $data['name'] . lang("added_successfully"), 'status' => 1, 'resdata' => $resdata);
            }
        } elseif ($data['act'] == 'sub') {
            //保存
            Db::name('warehouse_area')->where('warehouse_id', $data['warehouse_id'])->delete();
            if (isset($data['arealist']) && $data['arealist']) {
                foreach ($data['arealist'] as $datakeys => $datavals) {
                    if ($datavals['id']) {
                        $update['id'] = $datavals['id'];
                        $update['warehouse_id'] = $datavals['warehouse_id'];
                        $update['type_id'] = $datavals['type_id'];
                        $update['name'] = $datavals['name'];
                        $update['volume'] = $datavals['volume'];
                        $update['remarks'] = $datavals['remarks'];
                        $update['create_at'] = $datavals['create_at'];
                        $update['update_at'] = $datavals['update_at'];
                        $update['update_id'] = $datavals['update_id'];
                        $update['create_id'] = $datavals['create_id'];
                        Db::name('warehouse_area')->insert($update);
                    } else {
                        Db::name('warehouse_area')->strict(false)->insert($datavals);
                    }
                }
                $retid = 1;
            } else {
                $retid = 1;
            }
            if ($retid) {
                return array('msg' => lang("edited_successfully"), 'status' => 1);
            } else {
                return array('msg' => lang("edit_failed"), 'status' => 0);
            }
        }
    }

    //设置仓库的距离
    public function settingadddel($data)
    {
        if ($data['act'] == 'setingsub') {
            $arrinsert = array();
            //表示含有数据提交过来
            Db::name('warehouse_distance')->where('warehouse_id', $data['warehouse_id'])->delete();
            if (isset($data['cangkulist']) && $data['cangkulist']) {
                //重新写入数据
                foreach ($data['cangkulist'] as $datakeys => $datavals) {
                    if ($datavals['id']) {
                        //更新数据
                        $update['id'] = $datavals['id'];
                        $update['warehouse_target_id'] = $datavals['warehouse_target_id'];
                        $update['days'] = $datavals['days'];
                        $update['warehouse_id'] = $datavals['warehouse_id'];
                        Db::name('warehouse_distance')->insert($update);
                    } else {
                        //添加数据
                        Db::name('warehouse_distance')->strict(false)->insert($datavals);
                    }
                }
                $retid = 1;
            } else {
                $retid = 1;
            }
            if ($retid) {
                return array('msg' => lang("edited_successfully"), 'status' => 1);
            } else {
                return array('msg' => lang("edit_failed"), 'status' => 0);
            }
        }
    }

    //处理仓库详情的数据
    public function getdatastore($res)
    {
        $warehousedata = getables('warehouse', null, 'id,name');
        if (isset($res['warehouseid'])) {
            //不带搜索条件 获取该仓库下的数据
            $mapstore['warehouse_id'] = $res['warehouseid'];
        }
        if (isset($res['searchText']) && $res['searchText']) {
            //说明含有搜索条件 获取的是产品所在的仓库的数据
            $proList = getProList($res, $res['lang']);
            $procharid = implode(',', array_column($proList, 'id'));
            $mapstore['prochar_id'] = array('in', $procharid);
            $mapstore['warehouse_id'] = array('gt', 0);
        }
        if (!isset($res['searchText']) && !isset($res['warehouseid'])) {
            return array('warehousedata' => $warehousedata);
        } else {
            $saledata = Db::name('store')->Distinct(true)->field('warehouse_id,pro_id,prochar_id')->page($res['page'], $res['pageSize'])->where($mapstore)->select();
            $count = count(Db::name('store')->Distinct(true)->field('warehouse_id,pro_id,prochar_id')->where($mapstore)->select());

            //获取每一个产品的相关数据
            foreach ($saledata as $saledatakey => $saledataval) {
                $mapwarse['place_id'] = $mapwarse['warehouse_id'] = 0;
                //产品的总库存 仓库为0 ，位置为0
                $mapwarse['pro_id'] = $saledataval['pro_id'];
                $mapwarse['prochar_id'] = $saledataval['prochar_id'];
                $instore = Db::name('store')->where($mapwarse)->find();
                $saledata[$saledatakey]['qty'] = $instore['qty'] ? $instore['qty'] : 0;//产品总库存数量

                //该仓库的数据
                $mapwarse['warehouse_id'] = $saledataval['warehouse_id'];
                $infostores = Db::name('store')->where($mapwarse)->find();
                $saledata[$saledatakey]['qtys'] = $infostores['qty'];//该仓库产品数量
                $saledata[$saledatakey]['sale_qtys'] = $infostores['sale_qty'];//该仓库下的销售数量

                unset($mapwarse['place_id']);
                $mapwarse['check_id'] = array('gt', 0);
                //确认仓库遗失数量
                $saledata[$saledatakey]['missing_qty'] = Db::name('store_missing')->where($mapwarse)->sum('missing_qty');
                $mapwarse['check_id'] = 0;
                //未确认仓库遗失数量
                $saledata[$saledatakey]['missing_qtys'] = Db::name('store_missing')->where($mapwarse)->sum('missing_qty');

                //仓库调账数量（表示的是这个产品在这个仓库调整的总数量）
                unset($mapwarse['check_id']);
                unset($mapwarse['warehouse_id']);
                $adjustids = implode(',', array_column(getables('store_adjust', ['warehouse_id' => $saledataval['warehouse_id']], 'id'), 'id'));
                $mapwarse['store_adjust_id'] = array('in', $adjustids);
                $saledata[$saledatakey]['adjust_qty'] = Db::name('store_adjust_detail')->where($mapwarse)->sum('qty');
                unset($mapwarse['store_adjust_id']);
                //产品的数据
                $saledata[$saledatakey]['pro_data'] = getProAndProchar($saledataval, $res['lang'], 48);
                $saledata[$saledatakey]['warsename'] = getValue('warehouse', ['id' => $saledataval['warehouse_id']], 'name');//仓库名称
            }
            return array('data' => $saledata, 'count' => $count);
        }
    }

    //处理仓库的详情点击数据
    public function getdetails($res)
    {
        $topdata = getProAndProchar($res, $res['lang'], 48);
        //状态
        $map['warehouse_id'] = $res['warehouseid'];$map['place_id'] = 0;
        $map['pro_id'] = $res['pro_id'];
        $map['prochar_id'] = $res['prochar_id'];
        //获取的是这个仓库的总数和这个仓库已经销售的数量
        $storeinfo = Db::name('store')->field('qty,sale_qty')->where($map)->find();

        unset($map['place_id']);
        $map['check_id'] = array('gt', 0);
        //这个仓库遗失数量
        $storeinfo['missing_qty'] = Db::name('store_missing')->where($map)->sum('missing_qty');

        //仓库的调整数量
        $adjustids = implode(',', array_column(getables('store_adjust', ['warehouse_id' => $res['warehouseid']], 'id'), 'id'));
        $mapwarse['store_adjust_id'] = array('in', $adjustids);
        $storeinfo['adjust_qty'] = Db::name('store_adjust_detail')->where($mapwarse)->sum('qty');//调整数量

        //获取产品存放的位置及数量
        unset($map['check_id']);
        $map['place_id'] = array('gt', 0);
        $proplace = Db::name('store')->where($map)->field('qty,place_id')->select();
        foreach ($proplace as $proplacekey => $proplaceval) {
            $proplace[$proplacekey]['place_name'] = getValue('warehouse_place', ['id' => $proplaceval['place_id']], 'name');
        }

        //库存区域(nt_store2area)
        unset($map['place_id']);
        $store2area = Db::name('store2area')->where($map)->field('qty,area_id')->select();
        foreach ($store2area as $store2areakey => $store2areaval) {
            $store2area[$store2areakey]['area_name'] = getValue('warehouse_area', ['id' => $store2areaval['area_id']], 'name');
        }
        return array('topdata' => $topdata, 'leftdata' => $storeinfo, 'placedata' => $proplace, 'areadata' => $store2area);
    }

    //处理仓库中的调整的点击
    public function getadjusts($res)
    {
        $topdata = getProAndProchar($res, $res['lang'], 48);
        $map['warehouse_id'] = $res['warehouseid']; $map['place_id'] = 0;
        $map['pro_id'] = $res['pro_id']; $map['prochar_id'] = $res['prochar_id'];
        //仓库该产品的库存和销售数量
        $warsedata = Db::name('store')->where($map)->field('qty,sale_qty')->find();
        $warsedata['warsename'] = getValue('warehouse', ['id' => $res['warehouseid']], 'name');
        return array('topdata' => $topdata, 'warsedata' => $warsedata);
    }

    //处理调整数据的保存
    public function saveadjusts($res)
    {
        $ckdata = notEmpty(['qty' => '数量', 'remark' => '调整备注']);
        if ($ckdata['status'] == 2) {
            return $ckdata;
        }
        if (!is_numeric($res['qty'])) {
            return array('status' => 2, 'msg' => '调整数量不是一个数字');
        }
        //将数据写入调整的数据中去
        $res['create_id'] = $res['update_id'] = session('userid');
        $res['create_at'] = $res['update_at'] = time();
        $adjustid = Db::name('store_adjust')->strict(false)->insertGetId($res);
        $res['store_adjust_id'] = $adjustid;
        $detailids = Db::name('store_adjust_detail')->strict(false)->insert($res);
        if ($detailids) {
            return array('msg' => $res['qty'] . lang("added_successfully"), 'status' => 1);
        } else {
            return array('msg' => $res['qty'] . lang("add_failed"), 'status' => 0);
        }
    }

    //处理仓库调货单数据
    public function gettransfer($res)
    {
        $warehousedata = getables('warehouse', null, 'id,name');//仓库名称
        if (isset($res['warehouseid'])) {
            //调货指令
            if ($res['status'] == 1) {
                //获取调货单-明细
                $mapwarse['warehouse_id'] = $stdmap['warehouse_id'] = $res['warehouseid'];
                $stdmap['store_order_id'] = 0;
                $order_detail = Db::name('store_order_detail')->where($stdmap)->page($res['page'], $res['pageSize'])->select();
                $count = Db::name('store_order_detail')->where($stdmap)->count();
                $mapwarse['place_id'] = 0;
                $keys = array();
                foreach ($order_detail as $order_detailkey => $order_detailval) {
                    $mapwarse['pro_id'] = $order_detailval['pro_id'];
                    $mapwarse['prochar_id'] = $order_detailval['prochar_id'];
                    $storeqty = getValue('store', $mapwarse, 'qty');

                    $order_detail[$order_detailkey]['storeqty'] = $storeqty ? $storeqty : 0;//该仓库产品数量
                    //产品数据
                    $order_detail[$order_detailkey]['prodata'] = getProAndProchar($order_detailval, $res['lang'], 48);
                    $order_detail[$order_detailkey]['create_name'] = getinfo($order_detailval['create_id'], 'admin')['nickname'];//申请者
                    $order_detail[$order_detailkey]['create_date'] = getTimeDate($order_detailval['create_at'], 12);
                    array_push($keys, $order_detailkey);
                }
                //获取的是取货人
                $mapids['status'] = 0;//必须是空闲下的员工
                $mapids['warehouse_id'] = $res['warehouseid'];//必须是本仓库
                $takename = getables('deliveryman', $mapids, 'admin_id');//取货人
                foreach ($takename as $takenamekey => $takenameval) {
                    $getadmin = getinfo($takenameval['admin_id'], 'admin', 'position_id,nickname');
                    $takename[$takenamekey]['admin_name'] = $getadmin['nickname'];
                    if ($getadmin['position_id'] == 37) {
                        //送货队长
                        $takename[$takenamekey]['postion'] = 'L';
                    } elseif ($getadmin['position_id'] == 31) {
                        //司机
                        $takename[$takenamekey]['postion'] = 'M';
                    } elseif ($getadmin['position_id'] == 39) {
                        //实习送货员
                        $takename[$takenamekey]['postion'] = 'P';
                    }
                }
                return array('data' => $order_detail, 'count' => $count, 'keys' => $keys, 'takename' => $takename);
            } elseif ($res['status'] == 2) {
                //调货单
                $stdmap['source_id'] = $res['warehouseid'];
                $store_order = Db::name('store_order')->where($stdmap)->page($res['page'], $res['pageSize'])->select();
                $count = Db::name('store_order')->where($stdmap)->count();
                foreach ($store_order as $store_orderkey => $store_orderval) {
                    //发货仓
                    $store_order[$store_orderkey]['source_name'] = getValue('warehouse', ['id' => $store_orderval['source_id']], 'name');
                    //获取产品的相关数据
                    $prodatas = $this->getprodatas($store_orderval, $res['lang']);
                    $store_order[$store_orderkey]['pronum'] = $prodatas['sumpronum'];//产品数量
                    $store_order[$store_orderkey]['ctnnum'] = $prodatas['sumctnnum'];//产品箱数
                    $store_order[$store_orderkey]['m3num'] = $prodatas['summ3num'];//产品体积
                    $store_order[$store_orderkey]['kgsnum'] = $prodatas['sumkgsnum'];//产品重量
                    //打印人，时间
                    if ($store_orderval['print_id']) {
                        $store_order[$store_orderkey]['print_name'] = getinfo($store_orderval['print_id'], 'admin')['nickname'];//打印人
                        $store_order[$store_orderkey]['print_date'] = getTimeDate($store_orderval['print_at'], 12);
                    }
                    //已收货，以及收货时间
                    if ($store_orderval['received_id']) {
                        $store_order[$store_orderkey]['receive_name'] = getinfo($store_orderval['received_id'], 'admin')['nickname'];//收获者
                        $store_order[$store_orderkey]['receive_date'] = getTimeDate($store_orderval['received_at'], 12);
                    }
                    //创建
                    $store_order[$store_orderkey]['create_name'] = getinfo($store_orderval['create_id'], 'admin')['nickname'];//创建者
                    $store_order[$store_orderkey]['create_date'] = getTimeDate($store_orderval['create_at'], 12);
                    //更新时间
                    $store_order[$store_orderkey]['update_name'] = getinfo($store_orderval['update_id'], 'admin')['nickname'];//编辑者
                    $store_order[$store_orderkey]['update_date'] = getTimeDate($store_orderval['update_at'], 12);
                }
                return array('data' => $store_order, 'count' => $count);
            }
        } else {
            return array('warehousedata' => $warehousedata);
        }

    }

    //获取调货单的产品总量
    protected function getprodatas($store_orderval, $lang)
    {
        //产品数量
        $sumpronum = count(Db::name('store_order_detail')->distinct(true)->field('prochar_id')->where(['store_order_id' => $store_orderval['id']])->select());
        $datapro = getables('store_order_detail', ['store_order_id' => $store_orderval['id']]);
        $sumkgsnum = $summ3num = $sumctnnum = 0;//产品重量、产品体积、产品箱数
        foreach ($datapro as $dataprokey => $dataproval) {
            //产品信息
            $prodata = getProAndProchar($dataproval, $lang, 48);
            $ctnnum = ceil($dataproval['qty'] / $prodata['prochar_qty']);//箱数
            $m3num = $ctnnum * $prodata['ctn_m3'];//体积
            $kgsnum = ($prodata['ctn_kgs'] / $prodata['prochar_qty']) * $dataproval['qty'];//产品重量
            $sumctnnum += $ctnnum;
            $summ3num += $m3num;
            $sumkgsnum += $kgsnum;
        }
        return array(
            'sumpronum' => $sumpronum,
            'sumctnnum' => $sumctnnum,
            'summ3num' => $summ3num,
            'sumkgsnum' => $sumkgsnum,
        );
    }

    //调度数据的保存
    public function savetransfer($res)
    {
        $ckdata = notEmpty(['source_id' => '仓库', 'leader' => '取货人']);
        if ($ckdata['status'] == 2) {
            return $ckdata;
        }
        if (!isset($res['team'])) {
            return array('msg' => '组员不能为空', 'status' => 2);
        }
        //取货人职务必须要是司机或者队长
        $position_id = getValue('admin', ['id' => $res['leader']], 'position_id');
        if (!in_array($position_id, ['31', '37'])) {
            return array('msg' => '取货人员必须是司机或者队长', 'status' => 2);
        }
        $postionids = array();//组员的职位
        foreach ($res['team'] as $teamkey => $temval) {
            $pod = getValue('admin', ['id' => $temval], 'position_id');
            array_push($postionids, $pod);
        }
        if (!in_array('31', $postionids)) {
            return array('msg' => '选择的组员必须要有司机', 'status' => 2);
        }
        $insert['warehouse_id'] = $res['warehouse_id'];//收货仓库ID
        $insert['source_id'] = $res['source_id'];//源发货仓库id
        $insert['create_id'] = $insert['update_id'] = session('userid');
        $insert['create_at'] = $insert['update_at'] = time();
        $insertid = Db::name('store_order')->insertGetId($insert);
        //数据的写入
        foreach ($res['tiaolist'] as $keys => $vals) {
            //更新值
            $update['store_order_id'] = $insertid;//调货单id
            $update['source_id'] = $res['source_id'];//源发货仓库id
            Db::name('store_order_detail')->where('id', $vals['id'])->update($update);
        }
        //设置这个销售仓库的取货小组人员
        foreach ($res['team'] as $teamkeys => $teamvals) {
            $insertteam['warehouse_id'] = $res['source_id'];
            $insertteam['order_id'] = $insertid;
            $insertteam['admin_id'] = $teamvals;
            $pod = getValue('admin', ['id' => $teamvals], 'position_id');
            $insertteam['position_id'] = $pod;
            $insertteam['leader'] = 0;
            Db::name('store_order_team')->insert($insertteam);
            //改变送货员工的工作状态
            $deliupdate['status'] = 1;
            $deliupdate['start_at'] = time();
            Db::name('deliveryman')->where('admin_id', $teamvals)->update($deliupdate);
        }
        //判断取货人是否存在取货小组中
        $mapleader['warehouse_id'] = $res['source_id'];
        $mapleader['order_id'] = $insertid;
        $mapleader['admin_id'] = $res['leader'];
        $storeleader = getables('store_order_team', $mapleader);
        if ($storeleader) {
            //改变状态
            Db::name('store_order_team')->where($mapleader)->update(['leader' => 1]);
        } else {
            //添加一条数据
            $deliinsert['warehouse_id'] = $res['source_id'];
            $deliinsert['order_id'] = $insertid;
            $deliinsert['admin_id'] = $res['leader'];
            $pod = getValue('admin', ['id' => $res['leader']], 'position_id');
            $deliinsert['position_id'] = $pod;
            $deliinsert['leader'] = 1;//队长
            Db::name('store_order_team')->where('admin_id', $teamvals)->update($deliinsert);
        }
        //改变员工的工作状态
        return array('msg' => '调货成功', 'status' => 1);
    }

    //调货单的删除
    public function deltransfer($res)
    {
        if ($res['code'] == 1) {
            //调货指令的删除
            $retrole = Db::name('store_order_detail')->where('id', $res['id'])->delete();
        } elseif ($res['code'] == 2) {
            //如果这个调货单已经有货物调出或者收货入库，无法删除
            $infoorder = getinfo($res['id'], 'store_order');
            if ($infoorder['takeout_at'] > 0 || $infoorder['received_at'] > 0) {
                return array('msg' => '该调货单已调出或者已收货入库', 'status' => 2);
            }
            $retrole = Db::name('store_order_detail')->where(['store_order_id' => $res['id']])->update(['store_order_id' => 0, 'source_id' => 0]);
            $storedata = Db::name('store_order_team')->where('order_id', $res['id'])->select();//取货的相关人员
            foreach ($storedata as $storedatakey => $storedataval) {
                //调整状态和开始任务时间
                Db::name('deliveryman')->where('admin_id', $storedataval['admin_id'])->update(['status' => 0, 'start_at' => 0]);
            }
            //取货小组的删除
            Db::name('store_order_team')->where('order_id', $res['id'])->delete();
            //调货单删除
            Db::name('store_order')->where(['id' => $res['id']])->delete();
        }
        if ($retrole !== false) {
            return array('msg' => $res['name'] . lang("deleted_successfully"), 'status' => 1);
        } else {
            return array('msg' => $res['name'] . lang("failed_to_delete"), 'status' => 0);
        }
    }

    //调货单的查看
    public function transdetail($res)
    {
        $infoorder = $this->getorder($res['id']);
        //调货清单下的产品
        $prodatares = Db::name('store_order_detail')->where(['store_order_id' => $res['id']])->select();
        $mapwarse['warehouse_id'] = $res['warehouse_id'];
        $mapwarse['place_id'] = 0;
        foreach ($prodatares as $prodatareskey => $prodataresval) {
            $mapwarse['pro_id'] = $prodataresval['pro_id'];
            $mapwarse['prochar_id'] = $prodataresval['prochar_id'];
            $prodatares[$prodatareskey]['storeqty'] = getValue('store', $mapwarse, 'qty');//该仓库库存数量
            $prodatares[$prodatareskey]['prodata'] = getProAndProchar($prodataresval, $res['lang'], 48);
        }
        return array('topdata' => $infoorder, 'prodata' => $prodatares);
    }

    //货物调出,收获入库 接口
    public function takeoutarraival($res)
    {
        $mapstatus = $this->getmapwhere($res['status']);
        $admin = session('admin');
        if ($res['status'] == 1 || $res['status'] == 3) {
            if (isset($res['dname'])) {
                $mapstatus['id'] = array("like", "%" . $res['dname'] . "%");
            }
            //以调货单为主查询
            $store_order = Db::name('store_order')->where($mapstatus)->page($res['page'], $res['pageSize'])->select();
            $count = Db::name('store_order')->where($mapstatus)->count();
            foreach ($store_order as $store_orderkey => $store_orderval) {
                //发货仓
                $store_order[$store_orderkey]['source_name'] = getValue('warehouse', ['id' => $store_orderval['source_id']], 'name');
                //收获仓
                $store_order[$store_orderkey]['warehouse_name'] = getValue('warehouse', ['id' => $store_orderval['warehouse_id']], 'name');
                //一个调货单只有一个取货人
                $maporder['leader'] = 1;
                $maporder['order_id'] = $store_orderval['id'];
                $take_id = getValue('store_order_team', $maporder, 'admin_id');
                $store_order[$store_orderkey]['take_name'] = getValue('admin', ['id' => $take_id], 'nickname');
                //获取产品的相关数据
                $prodatas = $this->getprodatas($store_orderval, $res['lang']);
                $store_order[$store_orderkey]['pronum'] = $prodatas['sumpronum'];//产品数量
                $store_order[$store_orderkey]['ctnnum'] = $prodatas['sumctnnum'];//产品箱数
                $store_order[$store_orderkey]['m3num'] = $prodatas['summ3num'];//产品体积
                $store_order[$store_orderkey]['kgsnum'] = $prodatas['sumkgsnum'];//产品重量
                //打印人，时间
                if ($store_orderval['print_id']) {
                    $store_order[$store_orderkey]['print_name'] = getinfo($store_orderval['print_id'], 'admin')['nickname'];//打印人
                    $store_order[$store_orderkey]['print_date'] = getTimeDate($store_orderval['print_at'], 12);
                }
                //已收货，以及收货时间
                if ($store_orderval['received_id']) {
                    $store_order[$store_orderkey]['receive_name'] = getinfo($store_orderval['received_id'], 'admin')['nickname'];//收获者
                    $store_order[$store_orderkey]['receive_date'] = getTimeDate($store_orderval['received_at'], 12);
                }
                //创建
                $store_order[$store_orderkey]['create_name'] = getinfo($store_orderval['create_id'], 'admin')['nickname'];//创建者
                $store_order[$store_orderkey]['create_date'] = getTimeDate($store_orderval['create_at'], 12);
                //更新时间
                $store_order[$store_orderkey]['update_name'] = getinfo($store_orderval['update_id'], 'admin')['nickname'];//编辑者
                $store_order[$store_orderkey]['update_date'] = getTimeDate($store_orderval['update_at'], 12);
            }
        } elseif ($res['status'] == 2 || $res['status'] == 4) {
            if (isset($res['dname'])) {
                $mapstatus['a.store_order_id'] = array("like", "%" . $res['dname'] . "%");
            }
            $store_order = Db::name('store_order_detail')->alias('a')->join('nt_store_order b', 'a.store_order_id=b.id', 'left')->field('a.*,b.source_id,b.create_at,b.takeout_id,b.takeout_at,b.received_id,b.received_at')->where($mapstatus)->page($res['page'], $res['pageSize'])->select();
            foreach ($store_order as $store_orderkey => $store_orderval) {
                $store_order[$store_orderkey]['prodata'] = getProAndProchar($store_orderval, $res['lang'], 48);
                if ($store_orderval['takeout_id']) {
                    //调出人，调出时间
                    $store_order[$store_orderkey]['takeout_name'] = getValue('admin', ['id' => $store_orderval['takeout_id']], 'nickname');
                    $store_order[$store_orderkey]['takeout_date'] = getTimeDate($store_orderval['takeout_at'], 12);
                }
                if ($store_orderval['received_id']) {
                    //收货人收货时间
                    $store_order[$store_orderkey]['received_name'] = getValue('admin', ['id' => $store_orderval['received_id']], 'nickname');
                    $store_order[$store_orderkey]['received_date'] = getTimeDate($store_orderval['received_at'], 12);
                }
            }
            $count = Db::name('store_order_detail')->alias('a')->join('nt_store_order b', 'a.store_order_id=b.id', 'left')->where($mapstatus)->count();
        }
        return array('data' => $store_order, 'count' => $count);
    }

    //设置相关条件
    protected function getmapwhere($status)
    {
        $mapwhere = array();
        switch ($status) {
            //货物调出（调货单）
            case '1':
                $mapwhere['takeout_id'] = 0;
                $mapwhere['takeout_at'] = 0;
                break;
            //货物调出（调出记录）
            case '2':
                $mapwhere['b.takeout_id'] = array('gt', 0);
                $mapwhere['b.takeout_at'] = array('gt', 0);
                break;
            //收货入库（调货单）
            case '3':
                $mapwhere['received_id'] = 0;
                $mapwhere['received_at'] = 0;
                break;
            //收货入库（收货记录）
            case '4':
                $mapwhere['b.received_id'] = array('gt', 0);
                $mapwhere['b.received_at'] = array('gt', 0);
                break;
        }
        return $mapwhere;
    }

    //点击确认出库接口
    public function gettakeoutorder($res, $code)
    {
        //顶部的信息
        $infoorder = $this->getorder($res['id']);
        //调货清单下的产品
        $prodatares = Db::name('store_order_detail')->where(['store_order_id' => $res['id']])->select();
        foreach ($prodatares as $prodatareskey => $prodataresval) {
            $prodatares[$prodatareskey]['place_id'] = '';//选择的仓库id
            $prodatares[$prodatareskey]['prodata'] = getProAndProchar($prodataresval, $res['lang'], 48);//产品信息
            //获取这个产品在这个仓库库存
            if ($code == 1) {
                //调出仓库 的库存信息
                $storepro = $this->getstore($prodataresval, $prodataresval['source_id'], $code);
            } else {
                //收货入库 的库存信息
                $storepro = $this->getstore($prodataresval, $prodataresval['warehouse_id'], $code);
            }
            $prodatares[$prodatareskey]['prostore'] = $storepro['prostore'];
            $prodatares[$prodatareskey]['countqty'] = $storepro['countqty'];
            $prodatares[$prodatareskey]['place_data'] = $storepro['place_data'];
        }
        return array('topdata' => $infoorder, 'prodata' => $prodatares);
    }

    //获取该产品在这个仓库的位置数据
    protected function getstore($prodataresval, $id, $code)
    {
        $mapstore['warehouse_id'] = $id;
        $mapstore['place_id'] = array('gt', 0);
        $mapstore['pro_id'] = $prodataresval['pro_id'];
        $mapstore['prochar_id'] = $prodataresval['prochar_id'];
        $storedata = getables('store', $mapstore, 'qty,place_id');
        //列出符合要求的仓库id
        foreach ($storedata as $storedatakey => $storedataval) {
            $storedata[$storedatakey]['place_name'] = getValue('warehouse_place', ['id' => $storedataval['place_id']], 'name');
        }
        $mapstore['place_id'] = 0;
        //该产品在这个仓库的总库存
        $countqty = getValue('store', $mapstore, 'qty');
        if ($code == 1) {
            $place_ids = array_column($storedata, 'place_id');
            $mapplace['id'] = ['in', $place_ids];
            //调出的位置必须要满足这个仓库这个位置位置有这个产品
            $place_data = getables('warehouse_place', $mapplace, 'id,name');
        } else {
            //收货仓
            $mapplace['warehouse_id'] = $id;
            //收货位置满足这个仓库下的位置
            $place_data = getables('warehouse_place', $mapplace, 'id,name');
        }
        return array('prostore' => $storedata, 'countqty' => $countqty, 'place_data' => $place_data);
    }

    //处理产品出库
    public function savetakedata($res)
    {
        $arrdata = array();
        foreach ($res['prodatas'] as $keys => $vals) {
            if (!$vals['place_id']) {
                return array('msg' => '位置不能为空', 'status' => 2);
                exit();
            }
            //调出产品数量小于位置数量提示
            $sumqtymap['warehouse_id'] = $vals['source_id'];//出库id
            $sumqtymap['place_id'] = $vals['place_id'];//选择出库的位置
            $sumqtymap['pro_id'] = $vals['pro_id'];
            $sumqtymap['prochar_id'] = $vals['prochar_id'];
            $sumqty = getValue('store', $sumqtymap, 'qty');//位置下产品数量
            if ($vals['qty'] > $sumqty) {
                return array('msg' => '该位置产品数量不够，请更换位置', 'status' => 2);
                exit();
            }
            $arrdata[] = array(
                'id' => $vals['id'],
                'source_id' => $vals['source_id'],
                'place_id' => $vals['place_id'],//这是选择的位置
                'pro_id' => $vals['pro_id'],
                'prochar_id' => $vals['prochar_id'],
                'qty' => $vals['qty'],
            );
        }
        //出仓只是仓库这个产品的数量减少
        foreach ($arrdata as $arrdatakey => $arrdataval) {
            $mapstore['warehouse_id'] = $arrdataval['source_id'];
            $mapstore['place_id'] = $arrdataval['place_id'];
            $mapstore['pro_id'] = $arrdataval['pro_id'];
            $mapstore['prochar_id'] = $arrdataval['prochar_id'];
            //该位置数量减少
            Db::name('store')->where($mapstore)->setDec('qty', $arrdataval['qty']);
            //该仓库数量减少
            $mapstore['place_id'] = 0;
            Db::name('store')->where($mapstore)->setDec('qty', $arrdataval['qty']);
            //更新这个产品出仓的位置
            Db::name('store_order_detail')->where('id', $arrdataval['id'])->update(['source_place_id' => $arrdataval['place_id']]);
        }
        $ressava = Db::name('store_order')->where('id', $res['id'])->update(['takeout_id' => session('userid'), 'takeout_at' => time()]);
        //更新送货人的送货记录
        if ($ressava !== false) {
            $this->savedeliveryman($res['id'], $res['lang'], 1);
        }
        return array('msg' => '出仓成功', 'status' => 1);
    }

    /*
     * 处理产品的入库
     */
    public function savearrivaldata($res)
    {
        $arrdata = array();
        foreach ($res['prodatas'] as $keys => $vals) {
            if (!$vals['place_id']) {
                return array('msg' => '位置不能为空', 'status' => 2);
                exit();
            }
            $arrdata[] = array(
                'id' => $vals['id'],
                'warehouse_id' => $vals['warehouse_id'],//入库id
                'pro_id' => $vals['pro_id'],
                'prochar_id' => $vals['prochar_id'],
                'place_id' => $vals['place_id'],
                'qty' => $vals['qty'],
            );
        }
        //入仓只是仓库这个产品的数量增加
        foreach ($arrdata as $arrdatakey => $arrdataval) {
            $insert['warehouse_id'] = $mapstore['warehouse_id'] = $arrdataval['warehouse_id'];
            $insert['place_id'] = $mapstore['place_id'] = $arrdataval['place_id'];
            $insert['pro_id'] = $mapstore['pro_id'] = $arrdataval['pro_id'];
            $insert['prochar_id'] = $mapstore['prochar_id'] = $arrdataval['prochar_id'];
            $insert['qty'] = $arrdataval['qty'];
            //判断这个入库的位置是否存在该产品
            $infostore = Db::name('store')->where($mapstore)->find();
            if ($infostore) {
                //该位置数量增加
                Db::name('store')->where($mapstore)->setInc('qty', $arrdataval['qty']);
            } else {
                //添加一条数据
                Db::name('store')->insert($insert);
            }
            //该仓库数量增加
            $insert['place_id'] = $mapstore['place_id'] = 0;
            $infocount = Db::name('store')->where($mapstore)->find();
            if ($infocount) {
                Db::name('store')->where($mapstore)->setInc('qty', $arrdataval['qty']);
            } else {
                Db::name('store')->insert($insert);
            }
            //更新这个产品入仓的位置
            Db::name('store_order_detail')->where('id', $arrdataval['id'])->update(['place_id' => $arrdataval['place_id']]);
        }
        //更新出货人和出货时间
        $savedata = Db::name('store_order')->where('id', $res['id'])->update(['received_id' => session('userid'), 'received_at' => time()]);
        if ($savedata !== false) {
            $this->savedeliveryman($res['id'], $res['lang'], 2);
        }
        return array('msg' => '入仓成功', 'status' => 1);
    }

    /*
     * $arrdata 数据
     * $orderid 调货id
     * $code 出库 入库
     * 本市送货（取货）速度=任务时长*25% /任务数量
     * 个人平均箱数 =箱数 / 参与人员的数量
     * 个人平均重量= 重量 / 参与人员的数量
     * 个人平均立方= 立方 / 参与人员的数量
     */
    protected function savedeliveryman($orderid, $lang, $code)
    {
        $storeinfo = getinfo($orderid, 'store_order');//调货单信息
        $datapro = getables('store_order_detail', ['store_order_id' => $orderid]);//调货单详情
        $store_orderdata = getables('store_order_team', ['order_id' => $orderid]);//调货单人员
        $mannum = count($store_orderdata);//参与人员数
        $sumctnnum = $summ3num = $sumkgsnum = 0;//箱数、体积、重量
        foreach ($datapro as $dataprokey => $dataproval) {
            $prodata = getProAndProchar($dataproval, $lang, 48);//产品信息
            $ctnnum = ceil($dataproval['qty'] / $prodata['prochar_qty']);//箱数
            $m3num = $ctnnum * $prodata['ctn_m3'];//体积
            $kgsnum = ($prodata['ctn_kgs'] / $prodata['prochar_qty']) * $dataproval['qty'];//产品重量
            $sumctnnum += $ctnnum;
            $summ3num += $m3num;
            $sumkgsnum += $kgsnum;
        }
        if ($code == 1) {
            //出仓
            if ($storeinfo['received_at'] > 0) {
                //已入仓，完成时间就是takeout_at（获取参与调货的送货人员）
                foreach ($store_orderdata as $store_orderdatakey => $store_orderdataval) {
                    $start_at = getValue('deliveryman', ['admin_id' => $store_orderdataval['admin_id']], 'start_at');//开始时间
                    //计算每一个送货员工的完成时间
                    $speed = $this->gettime($start_at, $storeinfo['takeout_at']);
                    $updateorderteam['speed'] = $speed;//完成时间
                    $ctns = $updateorderteam['ctn'] = $sumctnnum / $mannum;//平均箱数
                    $kgs = $updateorderteam['kgs'] = $sumkgsnum / $mannum;//平均重量
                    $m3s = $updateorderteam['m3'] = $summ3num / $mannum;//平均体积
                    Db::name('store_order_team')->where('admin_id', $store_orderdataval['admin_id'])->update($updateorderteam);
                    //改变员工的工作状态
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->update(['status' => 0, 'start_at' => 0]);
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setInc('working', $speed);//合计工作时间（秒）
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setInc('ctn', $ctns);//合计箱数
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setInc('kgs', $kgs);//合计重量
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setInc('m3', $m3s);//合计体积
                    //送货员工月记录表
                    $this->deliveryman_month($ctns, $kgs, $m3s, $speed, $store_orderdataval['admin_id'], $storeinfo['takeout_at']);
                }
            }
        } else {
            //入仓
            if ($storeinfo['takeout_at'] > 0) {
                //已出仓了，完成时间就是received_at
                foreach ($store_orderdata as $store_orderdatakey => $store_orderdataval) {
                    $start_at = getValue('deliveryman', ['admin_id' => $store_orderdataval['admin_id']], 'start_at');//开始时间
                    //计算每一个送货员工的完成时间
                    $speed = $this->gettime($start_at, $storeinfo['received_at']);
                    $updateorderteam['speed'] = $speed;//完成时间
                    $ctns = $updateorderteam['ctn'] = $sumctnnum / $mannum;//平均箱数
                    $kgs = $updateorderteam['kgs'] = $sumkgsnum / $mannum;//平均重量
                    $m3s = $updateorderteam['m3'] = $summ3num / $mannum;//平均体积
                    Db::name('store_order_team')->where('admin_id', $store_orderdataval['admin_id'])->update($updateorderteam);
                    //改变员工的工作状态
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->update(['status' => 0, 'start_at' => 0]);
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setInc('working', $speed);//合计工作时间（秒）
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setInc('ctn', $ctns);//合计箱数
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setInc('kgs', $kgs);//合计重量
                    Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setInc('m3', $m3s);//合计体积
                    // //送货员工月记录表
                    $this->deliveryman_month($ctns, $kgs, $m3s, $speed, $store_orderdataval['admin_id'], $storeinfo['received_at']);
                }
            }
        }
    }

    //计算完成时间
    public function gettime($startime, $endtime)
    {
        $startdate = date('Y-m-d', $startime);
        $enddate = date('Y-m-d', $endtime);
        $time18 = strtotime($startdate) + 64800;//当天18点
        $time22 = strtotime($startdate) + 79200;//当天22点
        //同一天
        if ($startdate == $enddate) {
            $time = $endtime - $startime;
        } else {
            //不在同一天
            if ($startime > $time18) {
                //开始时间在18点以后
                $time = $time22 - $startime;
            } else {
                //开始时间在18点之前
                $time = $time18 - $startime;
            }
        }
        return $time;//工作时长
    }

    /*
     * 送货员工月记录表
     * $ctns 箱数
     * $kgs 重量
     * $m3s 体积
     * $working 工作时间（秒）
     * $admin_id 用户id
     * $time 完成时间
     * $leaving 请假时间
     * $workout 不在岗时间
     */
    public function deliveryman_month($ctn, $kgs, $m3, $working, $admin_id, $time, $leaving = null, $workout = null)
    {
        $year = getTimeDate($time, 1);
        $month = getTimeDate($time, 2);
        $mapadmin['admin_id'] = $admin_id;
        $mapadmin['year'] = $year;
        $mapadmin['month'] = $month;
        $warehouse_id = getValue('deliveryman', ['admin_id' => $admin_id], 'warehouse_id');
        $deliadmin = Db::name('deliveryman_month')->where($mapadmin)->find();
        if (!$deliadmin) {
            //给当前员工生成月报
            $insert['warehouse_id'] = $warehouse_id;//仓库id
            $insert['admin_id'] = $admin_id;
            $insert['year'] = $year;
            $insert['month'] = $month;
            $insert['rank'] = '1';
            $insert['working'] = $working;
            $insert['orders'] = '1';
            $insert['ctn'] = $ctn;
            $insert['kgs'] = $kgs;
            $insert['m3'] = $m3;
            Db::name('deliveryman_month')->insert($insert);
        } else {
            //更新当前员工的月报
            $ctnsum = ($deliadmin['orders'] * $deliadmin['ctn'] + $ctn) / ($deliadmin['orders'] + 1);
            $kgssum = ($deliadmin['orders'] * $deliadmin['kgs'] + $kgs) / ($deliadmin['orders'] + 1);
            $m3sum = ($deliadmin['orders'] * $deliadmin['m3'] + $m3) / ($deliadmin['orders'] + 1);
            Db::name('deliveryman_month')->where($mapadmin)->update([
                'working' => $deliadmin['working'] + $working,
                'ctn' => $ctnsum,
                'kgs' => $kgssum,
                'm3' => $m3sum,
                'orders' => $deliadmin['orders'] + 1,
            ]);
        }
    }

    //调货单数据
    public function getorder($id)
    {
        $infoorder = getinfo($id, 'store_order');
        //发货仓
        $infoorder['source_name'] = getValue('warehouse', ['id' => $infoorder['source_id']], 'name');
        //发货人发货时间
        $infoorder['store_ordername'] = getinfo($infoorder['create_id'], 'admin')['nickname'];
        $infoorder['store_orderdate'] = getTimeDate($infoorder['create_at'], 12);
        //收货仓
        $infoorder['warehouse_name'] = getValue('warehouse', ['id' => $infoorder['warehouse_id']], 'name');
        //一个调货单只有一个取货人
        $maporder['leader'] = 1;
        $maporder['order_id'] = $infoorder['id'];
        $take_id = getValue('store_order_team', $maporder, 'admin_id');
        $infoorder['take_name'] = getValue('admin', ['id' => $take_id], 'nickname');
        //打印人，时间
        if ($infoorder['print_id']) {
            $infoorder['print_name'] = getinfo($infoorder['print_id'], 'admin')['nickname'];//打印人
            $infoorder['print_date'] = getTimeDate($infoorder['print_at'], 12);
        }
        //已收货，以及收货时间
        if ($infoorder['received_id']) {
            $infoorder['receive_name'] = getinfo($infoorder['received_id'], 'admin')['nickname'];//收获者
            $infoorder['receive_date'] = getTimeDate($infoorder['received_at'], 12);
        }
        return $infoorder;
    }

    //收货入库撤消 货物调出撤消
    public function arrivaltakeoutrevoke($res, $code)
    {
        $admin = session('admin');
        $infoorderdata = getinfo($res['id'], 'store_order');
        //判断撤销按钮是否有权限
        if ($admin['position_id'] == 24) {
            //仓储主管，撤消10分钟
            $time = (time() - $infoorderdata['create_at']) / 60;
            if (ceil($time) > 10) {
                return array('msg' => lang("no_permission,_please_contact_administrator"), 'status' => 3);
            }
        } elseif ($admin['position_id'] == 1) {
            //管理员 撤消7天
            $time = (time() - $infoorderdata['create_at']) / 86400;
            if (ceil($time) > 7) {
                return array('msg' => lang("no_permission,_please_contact_administrator"), 'status' => 3);
            }
        } else {
            return array('msg' => lang("no_permission,_please_contact_administrator"), 'status' => 3);
        }
        $store_orderdata = getables('store_order_detail', ['store_order_id' => $res['id']]);
        $mapone['warehouse_id'] = $infoorderdata['source_id'];//调出仓库
        $maptwo['warehouse_id'] = $infoorderdata['warehouse_id'];//收货仓库
        foreach ($store_orderdata as $store_orderdatakey => $store_orderdataval) {
            $maptwo['pro_id'] = $mapone['pro_id'] = $store_orderdataval['pro_id'];
            $maptwo['prochar_id'] = $mapone['prochar_id'] = $store_orderdataval['prochar_id'];
            if ($code == 1) {
                //增加
                $mapone['place_id'] = $store_orderdataval['source_place_id'];//调出仓库位置
                //该位置进行增加
                Db::name('store')->where($mapone)->setInc('qty', $store_orderdataval['qty']);
                //该仓库增加
                $mapone['place_id'] = 0;
                Db::name('store')->where($mapone)->setInc('qty', $store_orderdataval['qty']);
                //位置撤销
                Db::name('store_order_detail')->where('id', $store_orderdataval['id'])->update(['source_place_id' => 0]);
            } else {
                //减少
                $maptwo['place_id'] = $store_orderdataval['place_id'];//收货入库位置
                //该位置进行减少
                Db::name('store')->where($maptwo)->setDec('qty', $store_orderdataval['qty']);
                //该仓库减少
                $maptwo['place_id'] = 0;
                Db::name('store')->where($maptwo)->setDec('qty', $store_orderdataval['qty']);
                //位置撤销
                Db::name('store_order_detail')->where('id', $store_orderdataval['id'])->update(['place_id' => 0]);
            }
        }
        //确定完成时间
        if ($infoorderdata['takeout_at'] > 0 && $infoorderdata['received_at'] > 0) {
            //才表示这个调货单是完成的状态，才会去修改取货小组，送货单，送货月报
            $store_orderdata = getables('store_order_team', ['order_id' => $res['id']]);
            if ($infoorderdata['takeout_at'] > $infoorderdata['received_at']) {
                $finsh_at = $infoorderdata['takeout_at'];//完成时间
            } else {
                $finsh_at = $infoorderdata['received_at'];//完成时间
            }
            $year = getTimeDate($finsh_at, 1);
            $month = getTimeDate($finsh_at, 2);
            foreach ($store_orderdata as $store_orderdatakey => $store_orderdataval) {
                //完成了才减个人
                Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setDec('working', $store_orderdataval['speed']);//工作时长
                Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setDec('ctn', $store_orderdataval['ctn']);//箱数
                Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setDec('kgs', $store_orderdataval['kgs']);//重量
                Db::name('deliveryman')->where('admin_id', $store_orderdataval['admin_id'])->setDec('m3', $store_orderdataval['m3']);//体积

                $mapmonth['year'] = $year;
                $mapmonth['month'] = $month;
                $mapmonth['admin_id'] = $store_orderdataval['admin_id'];
                Db::name('deliveryman_month')->where($mapmonth)->setDec('working', $store_orderdataval['speed']);//工作时间

                $deliver = Db::name('deliveryman_month')->where($mapmonth)->find();
                $ordernum = $deliver['orders'] - 1;
                if ($ordernum == 0) {
                    $updatedeliver['ctn'] = $updatedeliver['kgs'] = $updatedeliver['m3'] = $updatedeliver['orders'] = 0;
                } else {
                    $updatedeliver['ctn'] = ($deliver['ctn'] * $deliver['orders'] - $store_orderdataval['ctn']) / $ordernum;

                    $updatedeliver['kgs'] = ($deliver['kgs'] * $deliver['orders'] - $store_orderdataval['kgs']) / $ordernum;

                    $updatedeliver['m3'] = ($deliver['m3'] * $deliver['orders'] - $store_orderdataval['m3']) / $ordernum;
                    $updatedeliver['orders'] = $ordernum;
                }
                Db::name('deliveryman_month')->where($mapmonth)->updata($updatedeliver);
            }
            //无论是调货出库还是收获入库，只要撤消
            Db::name('store_order_team')->where('order_id', $res['id'])->update(['speed' => 0, 'ctn' => 0, 'kgs' => 0, 'm3' => 0]);
        }
        if ($code == 1) {
            Db::name('store_order')->where('id', $res['id'])->update(['takeout_id' => 0, 'takeout_at' => 0]);
        } else {
            Db::name('store_order')->where('id', $res['id'])->update(['received_id' => 0, 'received_at' => 0]);
        }
        return array('msg' => '撤消成功', 'status' => 1);
    }
}